import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class test6 {
    private JPanel jp;
    private JButton backbtn;
    private JTable table2;
    private String currentUsername; // 当前登录的用户名
    JFrame jf = new JFrame("歌曲列表");

    public test6(String username) {
        this.currentUsername = username;
        jf.setSize(500, 500);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
        backbtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new test3( currentUsername);
                jf.setVisible(false);
            }
        });
        showSongsOfSelectedPlaylist(currentUsername);
        table2.getColumnModel().getColumn(0).setPreferredWidth(100); // 第一列宽100
        table2.getColumnModel().getColumn(1).setPreferredWidth(150); // 第二列宽150
        table2.getColumnModel().getColumn(2).setPreferredWidth(200); // 第三列宽200
        jf.add(jp);
        jf.setVisible(true);
    }
    private void initComponents() {
        jp = new JPanel();
        backbtn = new JButton("返回");
        table2 = new JTable();

        jp.setLayout(new BorderLayout());
        jp.add(new JScrollPane(table2), BorderLayout.CENTER);
        jp.add(backbtn, BorderLayout.SOUTH);


    }
    private void showSongsOfSelectedPlaylist(String currentUsername) {
        String sql = "SELECT songid, title, artist FROM songs ";
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql", "root", "190825DLdl");
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            ResultSet resultSet = pstmt.executeQuery();
            String[] columnNames = {"歌曲ID", "歌名", "艺术家"};
            DefaultTableModel model = new DefaultTableModel(columnNames, 0);
            while (resultSet.next()) {
                String songId = resultSet.getString("songid");
                String title = resultSet.getString("title");
                String artist = resultSet.getString("artist");
                model.addRow(new Object[]{songId, title, artist});
            }
            table2.setModel(model);
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(jf, "数据库错误：" + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        new test6("6");
    }
}



